package main

import (
	"context"
	"fmt"
	"gitee.com/jinmingzhi/eth-learn/pkg/ethtool"
	"github.com/ethereum/go-ethereum/common"
	"math/big"
	"time"
)

var (
	client *ethtool.Client
	ctx    = context.Background()
)

func main() {
	var err error
	client, err = ethtool.Dial("http://localhost:8545")
	assert(err)

	go pull()
	go push()

	accounts, err := client.EthAccounts(ctx)
	assert(err)

	timer := time.Tick(5 * time.Second)
	for range timer {
		msg := map[string]interface{}{
			"from":  accounts[3],
			"to":    accounts[4],
			"value": big.NewInt(10000),
		}
		txid, err := client.EthSendTransaction(context.Background(), msg)
		assert(err)
		fmt.Println("trigger txid: ", txid.Hex())
	}
}

func pull() {
	fid, err := client.EthNewPendingTransactionFilter(ctx) //创建过滤器
	assert(err)

	timer := time.NewTicker(time.Second * 5)
	for range timer.C {
		hashes, err := client.EthGetFilterChanges(ctx, fid)
		assert(err)
		for _, txid := range hashes {
			fmt.Println("pull block hash: ", txid.Hex())
		}
	}
}

func push() {
	client, err := ethtool.Dial("ws://localhost:8545")
	assert(err)

	hashes := make(chan *common.Hash)
	sub, err := client.SubscribeNewPendingTransactions(ctx, hashes)
	assert(err)
	for {
		select {
		case err := <-sub.Err():
			panic(err)
		case hash := <-hashes:
			fmt.Println(fmt.Println("push block hash: ", hash.Hex()))
		}
	}
}

func assert(err error) {
	if err != nil {
		panic(err)
	}
}
